package server;

import java.net.Socket;
import java.util.Arrays;
import java.util.Random;
/**
 * MastermindServer Logic provides the implementation for the server to initialize a game
 * and handle guesses when they come through.
 * @author naggy
 *
 */

@SuppressWarnings("unused")
public class MastermindServerLogic {
	private Socket socket;
	private byte[] buffer;
	private boolean clientConnect;
	
	private char[] answer;
	private int guessCount;
	private boolean gameOver;
	
	
	public MastermindServerLogic(Socket socket){
		super();
		this.socket = socket;
		this.clientConnect = true;
		this.answer = setAnswer();
		this.guessCount = 0;
		this.gameOver = false;
	}
	
	
	public boolean isGameOver() {
		return gameOver;
	}


	public void setGameOver(boolean gameOver) {
		this.gameOver = gameOver;
	}


	public int getGuessCount() {
		return guessCount;
	}


	public void setGuessCount(int guessCount) {
		this.guessCount = guessCount;
	}


	private char[] setAnswer(){
		char[] colors = new char[6];
		
		//random instance
		Random rand = new Random();
		
		String alphabet = "RGBYOW";
		for(int i=0; i<6; i++){
			colors[i] = alphabet.charAt(rand.nextInt(alphabet.length()));
		}
		return colors;
		
	}
	
	/**
	 * Checks the answer and returns feedback
	 * @param recieved move sequence ie. RGBYYY
	 * @param answer ie. RGBYYY
	 */
	
	public String checkAnswer(char[] moveSequence){
		String feedback = "";
		for(int i = 0; i < 6; i++){
			if(moveSequence[i] == this.answer[i])
			{
				feedback += "B";
				moveSequence[i] = '#';
				//} else if(!moveSequence.contains(moveSequence[i])){
				//	moveSequence[i] = '#';
			}			
		}
		for(int x = 0; x < 6; x++){
			boolean found = false;
			for(int z = 0; z < 6; z++){
				if(moveSequence[z] == this.answer[x]){
					found = true;
				}
			}
			if(found){
				moveSequence[x] = '#';
				feedback += "W";
			}
		}
		this.guessCount += 1;
		checkGameState(feedback);
		return feedback;
		
	}
	
	/**
	 * Check if the game is over.
	 */
	public boolean checkGameState(String feedback){
		if(feedback.equals("BBBBBB")){
			return true;
		} else {
			return false;
		}
	}
}
